//constants
window.USEDTOKENS = 'USEDTOKENS';
window.SCORES = 'SCORES';
window.WORDS = 'WORDS';

window.gameReset = false;
window.waveReady = false;
window.gameExists = 'gameExists';
window.tokens = [];
window.usedTokens = [];
window.initialBoard = [];
window.leftTokens = [];

window.CELL_STATE = /^cell_([0-9]+)$/;
var pickmessgeElmt = null;
var playmessgeElmt = null;

function init() {
	makeTable();
	setTokenValues();
 	if (wave && wave.isInWaveContainer()) {
        wave.setStateCallback(stateUpdated);
		wave.setParticipantCallback(participantUpdated);
      }
}

function get(key) {
  var ret = null;
  if (wave) {
    ret = wave.getState().get(key); 
  }
  return ret;
}

function set(key, value) {
  var obj = {};
  obj[key] = value;
  if (wave) {
    wave.getState().submitDelta(obj);
  }  
}

function rm(key) {
  var obj = {};
  obj[key] = null;  
  if (wave) {
    wave.getState().submitDelta(obj);
  }  
}

function getViewerId() {
  var ret = null;
  if (wave) {
    ret = wave.getViewer().getDisplayName();
  }
  return ret;
}

 function hasExistingGame() {
  var ret = false;

  if (get(gameExists) != null) {
    ret = true;
  }

  return ret;
}

function participantUpdated()
{
	var participants = wave.getParticipants();
	var numPeople = participants.length;
	var setParticipant = false;
	if (parseInt(numPeople) > 0)
	{
	    for (var i = 0; i < parseInt(numPeople); i++)
		{
			participantId = participants[i].getId();
			if(!wave.getState().get(participantId))
			{
				if(participantId == wave.getViewer().getId())
				{
					set(participantId,'0');
					fillTokens();
					scrabble.drag.init();
				}	
				setParticipant = true;
			}
		}	
	}
	if(!setParticipant)
		updateScores();
}	

function updateScores()
{
	 var participants = wave.getParticipants();
	 var numPeople = participants.length;
     if (numPeople > 0) {
	 jQuery('#scoresTable').html("");
     for (var i = 0; i < numPeople; ++i) {
          var participant = participants[i];
		  participantName = participant.getDisplayName();
		  participantId = participant.getId();
		  participantImgURL = participant.getThumbnailUrl();
	      if (!participantName) {
            participantName = participant.getId();
          }
         	row = document.createElement('tr');
			row.setAttribute('id', participantId);
			cell1 = document.createElement('td');
			cell1.setAttribute('class', 'scoreBoard');
			cell1.setAttribute('align', 'left');
			img = document.createElement('img');
			img.setAttribute('src', participantImgURL);
			img.setAttribute('alt', participantId); 
			//celltext=document.createTextNode('<img src='+ participantImgURL + ' alt='+ participantId +'/>');
			cell1.appendChild(img);
			cell2 = document.createElement('td');
			cell2.setAttribute('class', 'scoreBoard');
			cell2.setAttribute('align', 'top');
			if(get(participantId))
				cell2.appendChild(document.createTextNode(get(participantId)));
			else cell2.appendChild(document.createTextNode('0'));	
			cell3 = document.createElement('td');
			cell3.setAttribute('id', participantId + "turn");
			cell3.setAttribute('class', 'scoreBoard');
			cell3.setAttribute('align', 'top');
			cell1.appendChild(document.createTextNode(participantName));
			row.appendChild(cell1);
			row.appendChild(cell2);
			row.appendChild(cell3);
			jQuery('#scoresTable').append(row);
		}
		 var currentUser = get('currentUser');
         var pickUser = get('pickTurn');
		 jQuery("[id=" + currentUser + "]").css({'background-color' : 'green'});
		 jQuery("[id=" + currentUser + "turn" + "]").text("Playing").fadeIn("slow");
		 
		 if(currentUser != wave.getViewer().getId())
		 	 disableBtns();
		 else enableBtns();
		 if(pickUser != wave.getViewer().getId())
		 	jQuery('#pick').attr('disabled', 'disabled');
		 else jQuery('#pick').removeAttr('disabled');
		 //showMessage(currentUser,"play")
		 //showMessage(pickUser,"pick");
		}
}

function showMessage(user, msg)
{
   var participants = wave.getParticipants();
   //var currentUser = get('currentUser');
  if (participants.length > 0 && user) {
	    for (var i = 0; i < participants.length; ++i) {
		if(participants[i].getId() == user)
		{
			if(msg == "pick")
			{
			var statusMsg =  new gadgets.MiniMessage("message", document.getElementById("messagebox1"));
			if(pickmessgeElmt)
				statusMsg.dismissMessage(pickmessgeElmt);
			var cell1 = document.createElement('div');
			cell1.setAttribute('id', 'messagetoDisplay');
			//cell1.setAttribute('align', 'center');
			var img = document.createElement('img');
			img.setAttribute('src', participants[i].getThumbnailUrl());
			img.setAttribute('align', 'center');
			img.setAttribute('alt', user); 	
			cell1.appendChild(img);
			if(user == wave.getViewer().getId())
			{
				text = "Your";
				 jQuery("[id=" + messagebox2 + "]").css({'background-color' : 'yellow'});
			}	
			else text = participants[i].getDisplayName() + "'s";	
			cell1.appendChild(document.createTextNode(text + " turn to " + msg));
			//var statusMsg =  new gadgets.MiniMessage("message", document.getElementById("messagebox"));
			//messgeElmt = statusMsg.createStaticMessage(jQuery("[id=" + currentUser + "]").html(), 3);
			pickmessgeElmt = statusMsg.createStaticMessage(cell1);
			break;
			}
			else if(msg == "play")
			{
			var statusMsg =  new gadgets.MiniMessage("message", document.getElementById("messagebox2"));
			if(playmessgeElmt)
				statusMsg.dismissMessage(playmessgeElmt);
			var cell1 = document.createElement('div');
			cell1.setAttribute('id', 'messagetoDisplay');
			cell1.setAttribute('align', 'center');
			var img = document.createElement('img');
			img.setAttribute('src', participants[i].getThumbnailUrl());
			//img.setAttribute('align', 'center');
			img.setAttribute('alt', user); 	
			cell1.appendChild(img);
			if(user == wave.getViewer().getId())
			{
				text = "Your";
				 jQuery("[id=" + messagebox2 + "]").css({'background-color' : 'yellow'});
			}	 
			else text = participants[i].getDisplayName() + "'s";	
			cell1.appendChild(document.createTextNode(text + " turn to " + msg));
			//var statusMsg =  new gadgets.MiniMessage("message", document.getElementById("messagebox"));
			//messgeElmt = statusMsg.createStaticMessage(jQuery("[id=" + currentUser + "]").html(), 3);
			playmessgeElmt = statusMsg.createStaticMessage(cell1);
			break;
			}
		}
	}
	}
}		


 function stateUpdated()
 {
   if (!wave) {
        return;
  }  
  
  if (!window.waveReady) {
    window.waveReady = true;
    initGame();
	updateScores();
    return;
  }  
 
 if (hasExistingGame()) {
	 window.usedTokens = JSON.parse(get(USEDTOKENS));
	 var keys = wave.getState().getKeys();
	 for (var i = 0; i < keys.length; ++i) {   
		var key = keys[i];
		 if (key.match(window.CELL_STATE)) {
			jQuery('#' + key).html(get(key));
			jQuery('#' + key).addClass('forbid');
		}
		}
	
	updateScores();
 }
 
}


function initGame()
{
 if (hasExistingGame()) {
	 window.usedTokens = JSON.parse(get(USEDTOKENS));
  var keys = wave.getState().getKeys();
  for (var i = 0; i < keys.length; ++i) {   
    var key = keys[i];
     if (key.match(window.CELL_STATE)) {
		jQuery('#' + key).html(get(key));
		jQuery('#' + key).addClass('forbid');
	}
	}
	
	var userId = wave.getViewer().getId() + 'currentCells';
	var userTokens = JSON.parse(get(userId));
	if(userTokens)
	{
		var tokens = jQuery(".tokens");
		for(var j = 0; j < userTokens.length;j++)
		{
		jQuery('#'+ tokens[j].id).html('<div class="drag token">' + userTokens[j] +'<sub class="subscripts">'+ getTokenValue(userTokens[j])+'</sub></div>');
		}
		scrabble.drag.init();
	}	
 }
 else
 {
 set(gameExists,'true');
 set(USEDTOKENS, JSON.stringify(window.usedTokens));
 set('tokenFree','free');
 set('currentUser', wave.getViewer().getId());
 set('pickTurn',wave.getViewer().getId());
 //leftTokens = getAllTokens();
 }
} 